package servlet;

import dao.DB;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.CookieStore;
import java.util.List;


//添加好友
@WebServlet("/addfri2")
public class addfri2 extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String fid =req.getParameter("fid");
        UserService userSer =new UserService();

        Cookie[] cookies = req.getCookies();
        String newToken = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("TOKEN")) {
                newToken = cookie.getValue();
            }
        }

        String uid = (String) DB.executeQuery("SELECT account FROM `user` WHERE token = ?" ,newToken).get(0).get("account");
        List list =DB.executeQuery(" SELECT * FROM `friend` WHERE userid = ? and  friendid= ?",uid,fid);
        List list1 =DB.executeQuery(" SELECT * FROM `friend` WHERE userid = ? and  friendid= ? and friStatus = 1",uid,fid);
        if (list.size() != 0 ){
            if (list1.size() !=0){
                req.getSession().setAttribute("addmsg","已存在该好友！");
                resp.sendRedirect("/page.jsp");
            }else{
                req.getSession().setAttribute("addmsg","已发送添加好友通知，请等待用户验证！");
                resp.sendRedirect("/page.jsp");
            }
        }else{
            userSer.addFriend(newToken,fid);
            req.getSession().setAttribute("addmsg","已发送添加好友通知，请等待用户验证！");
            resp.sendRedirect("/page.jsp");
        }



    }


}
